import CryptoJS from 'crypto-js';




/**
 * 随机生成32位的字符串
 * @returns {string}
 */
const generateRandomString = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  const charactersLength = characters.length;
  for (let i = 0; i < 32; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
};


/**
 * 随机生成uuid
 * @returns {string}
 */
export const generateUUID = () => {
      // 生成随机的WordArray对象
       const randomBytes = CryptoJS.lib.WordArray.random(16);
       // 将WordArray对象转换为十六进制字符串
       let hexString = randomBytes.toString(CryptoJS.enc.Hex);
       // // 格式化UUID字符串
       // // UUID格式为：xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
       // // 其中x是任意十六进制数字，y是8、9、a或b中的一个
       // hexString = hexString.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
       // // 设置UUID的版本号（第9位的字符，4表示随机生成的UUID）
       // hexString = hexString.substr(0, 13) + '4' + hexString.substr(14);
       // // 确保第17位是8、9、a或b中的一个
       // const variant = (parseInt(hexString.substr(16, 1), 16) & 0x3) | 0x8;
       // hexString = hexString.substr(0, 16) + variant.toString(16) + hexString.substr(17);
       return hexString;
};

/**
 * 随机生成aes 密钥
 * @returns {string}
 */
export const generateAesKey = () => {
  return CryptoJS.enc.Utf8.parse(generateRandomString());
};

/**
 * 加密base64
 * @returns {string}
 */
export const encryptBase64 = (str) => {
  return CryptoJS.enc.Base64.stringify(str);
};

/**
 * 解密base64
 */
export const decryptBase64 = (str) => {
  return CryptoJS.enc.Base64.parse(str);
};

/**
 * 使用密钥对数据进行加密
 * @param message
 * @param aesKey
 * @returns {string}
 */
export const encryptWithAes = (message, aesKey) => {
  const encrypted = CryptoJS.AES.encrypt(message, aesKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
};

/**
 * 使用密钥对数据进行解密
 * @param message
 * @param aesKey
 * @returns {string}
 */
export const decryptWithAes = (message, aesKey) => {
  const decrypted = CryptoJS.AES.decrypt(message, aesKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
};
